#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: vzresource.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  A vazaar resource

import uuid

from rdflib import URIRef

from vazaarlib.namespaces import *

class VazaarResource:
    def __init__(self):
        self.id = URIRef("vazaar://" + str(uuid.uuid4()))
        self.data = {}
        #shortcuts
        self.title = None
        self.mime = None
        self.last = None

    def __repr__(self):
        text = '(s) %s:\n' % self.id
        for p in self.data:
            text += '\t(p) ' + p + '\n'
            for value in self.data[p]:
                text += '\t\t (o) ' + value + '\n'

        return text

    def __update_shortcuts(self):
        try:
            self.title = self.data[NIE['title']]
            self.mime = self.data[NIE['mimeType']]
            self.last = self.data[NAO['lastModified']]
            self.url = self.data[NFO['fileUrl']]
            """
            for p in self.data:
                print str(p), str(self.data[p][0])
            """
        except:
            pass

    def add_triples(self, list):
        for p, o in list:
            try:
                list = self.data[p]
                list.append(o)
            except KeyError:
                list = []
                list.append(o)
            self.data[p] = list
        self.__update_shortcuts()


    def del_triples(self, tuplas):
        for p, o in tuplas:
            try:
                list = self.data[p]
                list.remove(o)
                self.data[p] = list
            except Exception, error:
                print error

    def update_triples(self, source, target):
        self.del_triples(source)
        self.add_triples(target)

    def get_value(self, p):
        return self.data[p]


if __name__ == '__main__':
    r = VazaarResource() # A vazaar resource

    list1 = [] # list 1 of triples
    list2 = [] # list 2 of triples
    source = [] # list of triples for source resource
    target = [] # list of triples for target resource

    source.append((NIE['title'], 'El mar'))
    target.append((NIE['title'], 'La mar'))

    list1.append((NIE['title'], 'El mar'))
    list1.append((NIE['mimeType'], 'text/plain'))
    list1.append((RDF.type, NFO['Image']))

    list2.append((NIE['title'], 'La mar'))

    # basic operations
    r.add_triples(list1)
    r.del_triples(list2)
    r.update_triples(source, target)

    print r

"""
    def add_triple(self, tupla):
        p, o = tupla
        try:
            list = self.data[p]
            list.append(o)
        except KeyError:
            list = []
            list.append(o)
        self.data[p] = list
"""
